package cn.cors;

import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;

import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * 类简介: CORS 构建,如果
 *
 * @Author: ShangGuan
 * @Time: 2024/05/29
 **/
public class CorsBuild {

    @Setter
    @Getter
    private String join = ",";
    private String includeUrl;

    /**
     * 运行的原
     */
    private String allowOrigin;
    /**
     * 运行的方法
     */
    private String allowMethods;
    /**
     * 最大时间
     */
    private String maxAge;
    /**
     * 允许标头
     */
    private String allowHeaders;

    private String CharacterEncoding = "UTF-8";

    public CorsBuild includeUrl(String... includeUrl) {
        this.includeUrl = Arrays.stream(includeUrl).collect(Collectors.joining(join));
        return this;
    }

    public CorsBuild allowOrigin(String... allowOrigin) {
        this.allowOrigin = Arrays.stream(allowOrigin).collect(Collectors.joining(join));
        return this;
    }

    public CorsBuild allowMethod(String... allowMethods) {
        this.allowMethods = Arrays.stream(allowMethods).collect(Collectors.joining(join));
        return this;
    }

    public CorsBuild maxAge(String... maxAge) {
        this.maxAge = Arrays.stream(maxAge).collect(Collectors.joining(join));
        return this;
    }

    public CorsBuild allowHeaders(String... allowHeaders) {
        this.allowHeaders = Arrays.stream(allowHeaders).collect(Collectors.joining(join));
        return this;
    }

    public CorsBuild CharacterEncoding(String... CharacterEncoding) {
        this.CharacterEncoding = Arrays.stream(CharacterEncoding).collect(Collectors.joining(join));
        return this;
    }

    public Cors build() {
        Cors cors;
        if (StrUtil.isBlank(CharacterEncoding)) {
            cors = new Cors(includeUrl, allowOrigin, allowMethods, maxAge, allowHeaders);
        } else {
            cors = new Cors(includeUrl, allowOrigin, allowMethods, maxAge, allowHeaders, CharacterEncoding);
        }
        cors.setJoin(join);
        return cors;
    }
}
